// 全局变量
let salesChart = null;
let inventoryChart = null;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    loadDashboardData();
    initializeCharts();
    loadAlerts();
    
    // 每30秒刷新一次数据
    setInterval(loadDashboardData, 30000);
});

// 加载仪表盘数据
async function loadDashboardData() {
    try {
        const [metrics, products, orders] = await Promise.all([
            fetch('/api/analytics/customer-insights').then(r => r.json()),
            fetch('/api/products').then(r => r.json()),
            fetch('/api/analytics/sales-trend?period=week').then(r => r.json())
        ]);

        // 更新关键指标
        document.getElementById('totalRevenue').textContent = `¥${metrics.total_revenue?.toLocaleString() || 0}`;
        document.getElementById('totalOrders').textContent = metrics.total_orders || 0;
        document.getElementById('totalProducts').textContent = products.total || 0;

        // 更新销售图表
        updateSalesChart(orders);
        
    } catch (error) {
        console.error('加载仪表盘数据失败:', error);
    }
}

// 初始化图表
function initializeCharts() {
    // 销售趋势图
    const salesCtx = document.getElementById('salesChart').getContext('2d');
    salesChart = new Chart(salesCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: '销售额',
                data: [],
                borderColor: '#6366f1',
                backgroundColor: 'rgba(99, 102, 241, 0.1)',
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '¥' + value.toLocaleString();
                        }
                    }
                }
            }
        }
    });

    // 库存状态图
    const inventoryCtx = document.getElementById('inventoryChart').getContext('2d');
    inventoryChart = new Chart(inventoryCtx, {
        type: 'doughnut',
        data: {
            labels: ['充足', '低库存', '缺货'],
            datasets: [{
                data: [0, 0, 0],
                backgroundColor: ['#10b981', '#f59e0b', '#ef4444']
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });

    loadInventoryData();
}

// 更新销售图表
function updateSalesChart(data) {
    if (!salesChart || !data) return;

    const labels = data.map(item => item.period);
    const values = data.map(item => parseFloat(item.total_revenue));

    salesChart.data.labels = labels;
    salesChart.data.datasets[0].data = values;
    salesChart.update();
}

// 加载库存数据
async function loadInventoryData() {
    try {
        const response = await fetch('/api/analytics/inventory-overview');
        const data = await response.json();

        const inventoryData = [
            data.in_stock || 0,
            data.low_stock || 0,
            data.out_of_stock || 0
        ];

        inventoryChart.data.datasets[0].data = inventoryData;
        inventoryChart.update();

        document.getElementById('lowStockAlerts').textContent = data.low_stock || 0;
    } catch (error) {
        console.error('加载库存数据失败:', error);
    }
}

// 加载预警信息
async function loadAlerts() {
    try {
        const response = await fetch('/api/products/alerts/low-stock');
        const alerts = await response.json();

        const alertsList = document.getElementById('alertsList');
        
        if (alerts.length === 0) {
            alertsList.innerHTML = `
                <div class="text-center text-muted py-4">
                    <i class="fas fa-check-circle fa-2x mb-2 text-success"></i>
                    <p>库存状态良好，暂无预警</p>
                </div>
            `;
            return;
        }

        alertsList.innerHTML = alerts.map(product => `
            <div class="alert-item p-3 mb-2 rounded">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="mb-1">${product.name}</h6>
                        <small class="text-muted">库存: ${product.stock_quantity} 件</small>
                    </div>
                    <div>
                        <button class="btn btn-sm btn-outline-primary" onclick="viewProduct(${product.id})">
                            查看详情
                        </button>
                    </div>
                </div>
            </div>
        `).join('');
    } catch (error) {
        console.error('加载预警信息失败:', error);
    }
}

// AI工具功能
async function generateDescriptions() {
    const button = event.target;
    button.innerHTML = '<span class="loading"></span> 生成中...';
    button.disabled = true;

    try {
        const response = await fetch('/api/products');
        const data = await response.json();
        
        if (data.products.length === 0) {
            alert('暂无商品需要生成描述');
            return;
        }

        // 为前3个商品生成描述
        const promises = data.products.slice(0, 3).map(product => 
            fetch('/api/ai/generate-description', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ productId: product.id })
            })
        );

        await Promise.all(promises);
        alert('商品描述生成完成！');
        
    } catch (error) {
        console.error('生成描述失败:', error);
        alert('生成失败，请稍后重试');
    } finally {
        button.innerHTML = '开始生成';
        button.disabled = false;
    }
}

async function smartPricing() {
    const button = event.target;
    button.innerHTML = '<span class="loading"></span> 分析中...';
    button.disabled = true;

    try {
        const response = await fetch('/api/products');
        const data = await response.json();
        
        // 为前5个商品提供定价建议
        const promises = data.products.slice(0, 5).map(product => 
            fetch('/api/ai/price-suggestion', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ productId: product.id })
            })
        );

        await Promise.all(promises);
        alert('定价建议生成完成！');
        
    } catch (error) {
        console.error('定价分析失败:', error);
        alert('分析失败，请稍后重试');
    } finally {
        button.innerHTML = '获取建议';
        button.disabled = false;
    }
}

async function analyzeReviews() {
    const button = event.target;
    button.innerHTML = '<span class="loading"></span> 分析中...';
    button.disabled = true;

    try {
        // 这里可以调用评论分析API
        alert('评论情感分析功能开发中...');
    } catch (error) {
        console.error('评论分析失败:', error);
        alert('分析失败，请稍后重试');
    } finally {
        button.innerHTML = '开始分析';
        button.disabled = false;
    }
}

// 数据同步
async function syncData() {
    const button = document.getElementById('syncBtn');
    const originalText = button.innerHTML;
    
    button.innerHTML = '<i class="fas fa-sync-alt fa-spin me-1"></i>同步中...';
    button.disabled = true;

    try {
        // 模拟同步过程
        await new Promise(resolve => setTimeout(resolve, 2000));
        
        await loadDashboardData();
        await loadAlerts();
        
        // 显示成功提示
        const toast = document.createElement('div');
        toast.className = 'position-fixed top-0 end-0 p-3';
        toast.style.zIndex = '1050';
        toast.innerHTML = `
            <div class="toast show" role="alert">
                <div class="toast-header">
                    <i class="fas fa-check-circle text-success me-2"></i>
                    <strong class="me-auto">同步成功</strong>
                    <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
                </div>
                <div class="toast-body">
                    数据已成功同步
                </div>
            </div>
        `;
        document.body.appendChild(toast);
        
        setTimeout(() => toast.remove(), 3000);
        
    } catch (error) {
        console.error('同步失败:', error);
    } finally {
        button.innerHTML = originalText;
        button.disabled = false;
    }
}

// 工具函数
function viewProduct(productId) {
    // 这里可以跳转到商品详情页
    console.log('查看商品:', productId);
}

// 事件监听
document.getElementById('syncBtn').addEventListener('click', syncData);

// 响应式处理
window.addEventListener('resize', function() {
    if (salesChart) salesChart.resize();
    if (inventoryChart) inventoryChart.resize();
});
